package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.service.LoveMusicService;
import com.example.onlinemusic.service.MusicService;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {

    @Autowired
    private MusicService musicService;

    @Autowired
    private LoveMusicService loveMusicService;

    @Value("${music.path}")
    private String musicPath;

    @RequestMapping(value = "/upload")
    public ResponseBodyMessage<Boolean> uploadMusic(@RequestParam  String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response){
        //1.检查是否登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null){
            System.out.println("没有登录");
            return new ResponseBodyMessage<>(-1,"请登录后上传",false);
        }

//        //2.先查询数据库中,是否有当前音乐(歌手加+歌名)
//        String fileName2 = file.getOriginalFilename();
//        int index1 = fileName2.lastIndexOf(".");
//        String title1 = fileName2.substring(0,index1);
//        Music music = musicService.select(title1,singer);
//        if(music!= null){
//
//            return new ResponseBodyMessage<>(-1,"歌曲重复不能上传",false);
//        }



        //2.上传文件到服务器
        String fileName = file.getOriginalFilename();//获取文件的名称

        String path = musicPath + fileName;

        File dest = new File(path);
        if (!dest.exists()){
            dest.mkdirs();
        }
        try{
            file.transferTo(dest);
            //return new ResponseBodyMessage<>(0,"上传成功",true);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败",false);
        }
        //return new ResponseBodyMessage<>(-1,"上传失败",false);

        //2.进行数据库的上传
        //1.准备数据 2.调用 insert
        // substring 是左闭右开 [0,4)意思就是拿到 0 到 3 下标的数据
        // lastIndexOf : 从后往前找第一个点
        int index = fileName.lastIndexOf(".");
        String title = fileName.substring(0,index);

        User user = (User) request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();

        String url = "music/get?path="+ title;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());

        try {
            int ret = 0;
            ret = musicService.dataInsert(title,singer,time,url,userid);
            if(ret == 1){
                response.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(0,"数据库上传成功",true);
            }else {
                return new ResponseBodyMessage<>(-1,"数据可上传失败",false);

            }
        } catch (Exception e) {
            e.printStackTrace();
            //报异常说明上传失败,要把服务上传的文件也要删掉
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库可上传失败",false);
        }


    }
    //播放音乐
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file = new File(musicPath + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    //删除单个音乐
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(String id){

        //1.检查音乐是否存在
        //1.1 把String 类型 id 变成整数
        int iid = Integer.parseInt(id);
        Music music = musicService.getMusicById(iid);
        if (music == null){
            return new ResponseBodyMessage<>(-1,"没有你要删除的音乐",false);
        }else {
            //2.如果存在要进行删除
            //2.1 删除数据库
            int ret = musicService.delete(iid);
            if(ret == 1){
                //2.2 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index+1);
                File file = new File(musicPath + fileName+".mp3");
                System.out.println(file.toPath());
                if(file.delete()){
                    //同步检查 lovemusic 表中是否存在这个音乐
                    loveMusicService.deleteLoveMusicByMusicId(iid);
                    return  new ResponseBodyMessage<>(0,"服务器当中的音乐删除成功",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器当中的音乐删除失败",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库当中的音乐删除失败",false);

            }

        }


    }

    //删除多首音乐
    @RequestMapping("deletesel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]")List<Integer> id){
        System.out.println("所有的ID : " + id);
        int sum = 0;

        for (int i = 0; i <id.size() ; i++) {
            int idd = id.get(i);
            Music music = musicService.getMusicById(idd);

            if (music == null){

                System.out.println("没有这个 id 的音乐");
                return new ResponseBodyMessage<>(-1,"没有你要删除的音乐",false);

            }else {
                int ret = musicService.delete(idd);

                if(ret == 1){

                    //2.2 删除服务器上的数据
                    int index = music.getUrl().lastIndexOf("=");
                    String fileName = music.getUrl().substring(index+1);
                    File file = new File(musicPath + fileName+".mp3");
                    System.out.println(file.toPath());
                    if(file.delete()){
                        //同步检查 lovemusic 表中是否存在这个音乐
                        loveMusicService.deleteLoveMusicByMusicId(idd);
                        sum += ret;
                    }else {
                        return new ResponseBodyMessage<>(-1,"服务器当中的音乐删除失败",false);
                    }
                }else{
                    return new ResponseBodyMessage<>(-1,"数据库当中的音乐删除失败",false);
                }

            }
        }

        if(sum == id.size()){
            return  new ResponseBodyMessage<>(0,"音乐删除成功",true);
        }else {
            return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
        }
    }

    //查询音乐
    @RequestMapping("/getmusic")
    public ResponseBodyMessage<List<Music>> getMusic(@RequestParam(required = false) String musicName){

        List<Music> musicList = null;
        if(musicName != null){
            musicList = musicService.getMusicByName(musicName);

        }else {
            musicList = musicService.getMusic();

        }
        return new ResponseBodyMessage(0,"查询到了所有的音乐",musicList);

    }



}
